package com.harmonk.firstscene.ui.model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.harmonk.firstscene.FirstSceneApplication
import com.harmonk.firstscene.db.entity.Road
import com.harmonk.firstscene.db.repository.RoadRepository
import kotlinx.coroutines.launch

class RoadViewModel(application: Application): AndroidViewModel(application) {
    private val roadRepository = (application as FirstSceneApplication).roadRepository
    private val _roads = MutableLiveData<List<Road>>()

    val roads: LiveData<List<Road>> = _roads
    private val _currentRoad = MutableLiveData<Road>()
    val currentRoad: LiveData<Road> = _currentRoad
    fun loadAllRoads() {
        viewModelScope.launch {
            try {
                roadRepository.getAllRoads().collect { roadList: List<Road> ->
                    _roads.postValue(roadList)
                }
            } catch (e: Exception) {
                _roads.postValue(emptyList())
                e.printStackTrace()
            }
        }
    }

    fun getRoadById(id: Long) {
        viewModelScope.launch {
            try {
                _currentRoad.postValue(roadRepository.getRoadById(id))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun insertRoad(road: Road) {
        viewModelScope.launch {
            try {
                roadRepository.insertRoad(road)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun updateRoad(road: Road) {
        viewModelScope.launch {
            try {
                roadRepository.updateRoad(road)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun deleteRoad(road: Road) {
        viewModelScope.launch {
            try {
                roadRepository.deleteRoad(road)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

class RoadViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
    override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(RoadViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return RoadViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}